/*
 * @lc app=leetcode.cn id=124 lang=javascript
 *
 * [124] 二叉树中的最大路径和
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxPathSum = function(root) {
    let sum=-Infinity
    let maxGain=function(root){
        if(!root)return 0
        let leftGain=Math.max(0,maxGain(root.left))
        let rightGain=Math.max(0,maxGain(root.right))
        let res=leftGain+rightGain+root.val
        sum=Math.max(res,sum)
        return root.val+Math.max(leftGain,rightGain)
    }
    maxGain(root)
    return sum
};
// @lc code=end

